<!DOCTYPE html>
<html>

<head>
    <title>文本播放器 ver0.7（修复加载问题版）</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }

        #content {
            margin: 20px;
            padding: 20px;
            line-height: 1.5em;
            transition: all 0.3s;
            overflow: auto;
            min-height: calc(150px * 1.5);
            border: 1px solid #666;
            background-color: #000000;
            color: #ffff00;
            border-radius: 5px;
        }

       .controls {
            margin: 20px;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
        }

       .config-group {
            border: 1px solid #666;
            padding: 15px;
            border-radius: 5px;
            background: #f0f0f0;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        button {
            min-width: 80px;
            padding: 8px 12px;
            border: none;
            background-color: #007BFF;
            color: white;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }

        input[type="number"],
        input[type="text"],
        select,
        textarea {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        #recitationInput {
            width: 100%;
            margin-top: 10px;
            height: 150px;
        }

       .missing {
            color: green;
        }

       .extra {
            color: red;
        }
    </style>
</head>

<body>
    <div id="content">请加载转换后的文本文件</div>

    <div class="controls">
        <div class="config-group">
            <input type="file" id="fileInput" accept=".txt">
            <button onclick="loadFile()">加载文件</button>
            <button onclick="clearLocalStorage()">清理历史记录</button>
            <br><br>
            播放速度(字/秒):
            <input type="number" id="speedRate" value="10" min="1" style="width: 60px">
            <br>
            最大行数: <input type="number" id="maxLines" value="5" min="1" style="width: 60px">
        </div>

        <div class="config-group">
            字体大小: <input type="number" id="fontSize" value="24" min="8" style="width: 60px">px
            <br>
            字体:
            <select id="fontSelect" onchange="applyStyles()">
                <option value="SimSun">宋体</option>
                <option value="Microsoft YaHei">微软雅黑</option>
                <option value="KaiTi">楷体</option>
            </select>
            <br><br>
            跳转到: <input type="text" id="jumpTo" style="width: 80px">
            <button onclick="jump()">跳转</button>
            <button onclick="jumpNext()">下一个</button>
            <button onclick="jumpPrevious()">上一个</button>
        </div>

        <div class="config-group">
            背景颜色: <input type="color" id="bgColor" value="#000000" onchange="applyStyles()">
            <br>
            文字颜色: <input type="color" id="textColor" value="#ffff00" onchange="applyStyles()">
            <br><br>
            <button onclick="togglePlay()" id="playBtn">▶ 播放</button>
            <button onclick="stop()">⏹ 停止</button>
            <br><br>
            <textarea id="recitationInput" placeholder="输入学生背诵的内容"></textarea>
            <button onclick="checkRecitation()">背诵检查</button>
        </div>
    </div>

    <script>
        let segments = [];
        let currentIndex = 0;
        let timer = null;
        let isPlaying = false;
        let lastLoadedFile = localStorage.getItem('lastLoadedFile');
        let lastLabel = localStorage.getItem('lastLabel');

        // 页面加载时尝试加载上次的文件并跳转到相应段落
        window.onload = function () {
            if (lastLoadedFile) {
                try {
                    parseFile(lastLoadedFile);
                    if (segments.length > 0) {
                        currentIndex = Math.min(currentIndex, segments.length - 1);
                        if (lastLabel) {
                            const index = segments.findIndex(s => s.label === lastLabel.toLowerCase());
                            if (index >= 0) {
                                currentIndex = index;
                            }
                        }
                        showSegment(currentIndex);
                    } else {
                        document.getElementById('content').innerHTML = "文件格式错误，尝试清理历史记录重新加载";
                    }
                } catch (error) {
                    console.error('文件解析出错:', error);
                    document.getElementById('content').innerHTML = "文件解析出错，请检查文件格式或清理历史记录";
                }
            }
        };

        // 解析文件内容，将其拆分为段落存储在 segments 数组中
        function parseFile(content) {
            segments = [];
            const lines = content.split(/\r?\n/);

            lines.forEach(line => {
                const trimmed = line.trim();
                if (trimmed) {
                    const colonIndex = trimmed.indexOf(':');
                    if (colonIndex > 0) {
                        const label = trimmed.substr(0, colonIndex).trim().toLowerCase();
                        const text = trimmed.substr(colonIndex + 1).trim();
                        if (label && text) {
                            segments.push({
                                label: label,
                                text: text
                            });
                        }
                    }
                }
            });
        }

        // 加载新文件
        function loadFile() {
            const file = document.getElementById('fileInput').files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function (e) {
                try {
                    parseFile(e.target.result);
                    localStorage.setItem('lastLoadedFile', e.target.result);
                    if (segments.length > 0) {
                        currentIndex = 0;
                        showSegment(currentIndex);
                    } else {
                        document.getElementById('content').innerHTML = "文件格式错误，请检查文件内容是否为 '标签:内容' 格式";
                    }
                } catch (error) {
                    console.error('文件加载出错:', error);
                    document.getElementById('content').innerHTML = "文件加载出错，请检查文件格式或尝试其他编码";
                }
            };
            reader.onerror = function () {
                console.error('文件读取错误:', reader.error);
                document.getElementById('content').innerHTML = "文件读取错误，请检查文件是否损坏或尝试其他编码";
            };
            reader.readAsText(file, 'UTF-8');
        }

        // 显示指定索引的段落
        function showSegment(index) {
            if (index < 0 || index >= segments.length) {
                document.getElementById('content').innerHTML = "请加载文件";
                return;
            }

            currentIndex = index;
            const segment = segments[index];
            document.getElementById('content').innerHTML = `
                <div style="color: #888; margin-bottom: 10px">${segment.label}</div>
                <div>${segment.text}</div>
            `;
            localStorage.setItem('lastLabel', segment.label);
            applyStyles();
        }

        // 应用样式设置，可根据实际情况修改
        function applyStyles() {
            const contentDiv = document.getElementById('content');
            contentDiv.style.fontSize = document.getElementById('fontSize').value + 'px';
            contentDiv.style.fontFamily = document.getElementById('fontSelect').value;
            contentDiv.style.color = document.getElementById('textColor').value;
            contentDiv.style.backgroundColor = document.getElementById('bgColor').value;
            contentDiv.style.maxHeight = `calc(${document.getElementById('maxLines').value} * 1.5em)`;
        }

        // 播放控制
        function togglePlay() {
            const btn = document.getElementById('playBtn');
            if (isPlaying) {
                clearTimeout(timer);
                btn.textContent = '▶ 继续';
                isPlaying = false;
            } else {
                btn.textContent = '⏸ 暂停';
                playNext();
                isPlaying = true;
            }
        }

        function playNext() {
            if (currentIndex >= segments.length - 1) {
                stop();
                return;
            }

            const nextIndex = currentIndex + 1;
            const duration = calculateDuration(segments[nextIndex].text);

            timer = setTimeout(() => {
                showSegment(nextIndex);
                playNext();
            }, duration);
        }

        function stop() {
            clearTimeout(timer);
            isPlaying = false;
            document.getElementById('playBtn').textContent = '▶ 播放';
        }

        // 跳转功能
        function jump() {
            const target = document.getElementById('jumpTo').value.trim();
            if (!target) return;

            let index;
            if (/^\d+$/.test(target)) {
                const n = parseInt(target);
                const targetLabel = `(${n}, ${n + 1}, ${n + 2})`;
                index = segments.findIndex(s => s.label === targetLabel.toLowerCase());
            } else {
                index = segments.findIndex(s => s.label === target.toLowerCase());
            }

            if (index >= 0 && index < segments.length) {
                stop();
                showSegment(index);
            } else {
                alert("未找到指定标签或索引超出范围");
            }
        }

        // 跳下一个
        function jumpNext() {
            stop();
            currentIndex = (currentIndex + 1) % segments.length;
            showSegment(currentIndex);
        }

        // 跳上一个
        function jumpPrevious() {
            stop();
            currentIndex = (currentIndex - 1 + segments.length) % segments.length;
            showSegment(currentIndex);
        }

        // 背诵检查
        function checkRecitation() {
            const input = document.getElementById('recitationInput').value;
            const currentText = segments[currentIndex].text;
            let result = '';
            let inputIndex = 0;

            for (let i = 0; i < currentText.length; i++) {
                if (inputIndex < input.length && currentText[i] === input[inputIndex]) {
                    result += currentText[i];
                    inputIndex++;
                } else {
                    result += `<span class="missing">${currentText[i]}</span>`;
                }
            }

            while (inputIndex < input.length) {
                result += `<span class="extra">${input[inputIndex]}</span>`;
                inputIndex++;
            }

            document.getElementById('content').innerHTML = `
                <div style="color: #888; margin-bottom: 10px">${segments[currentIndex].label}</div>
                <div>${result}</div>
            `;
        }

        // 计算显示时长
        function calculateDuration(text) {
            const speed = parseInt(document.getElementById('speedRate').value) || 10;
            const chnChars = text.match(/[\u4e00-\u9fa5]/g) || [];
            return Math.max(1000, (chnChars.length / speed) * 1000);
        }

        // 清理本地存储
        function clearLocalStorage() {
            localStorage.removeItem('lastLoadedFile');
            localStorage.removeItem('lastLabel');
            document.getElementById('content').innerHTML = "历史记录已清理，请重新加载文件";
        }
    </script>
</body>

</html>    